package ce.com.newbluedemo.k2;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.Toast;

import java.util.ArrayList;

import ce.com.cenewbluesdk.CEBC;
import ce.com.cenewbluesdk.entity.k2.K2_MixInfoStruct;
import ce.com.cenewbluesdk.entity.k2.K2_SendAlarmInfoStruct;
import ce.com.cenewbluesdk.entity.k2.K2_SendUserInfo;
import ce.com.cenewbluesdk.entity.k3.Send_Alarm_Info_Struct_K3;
import ce.com.cenewbluesdk.proxy.BleFactory;
import ce.com.cenewbluesdk.proxy.CEDevK2Proxy;
import ce.com.newbluedemo.R;

import static ce.com.newbluedemo.k2.LittleUtils.isInteger;

/**
 * Created by YaoBinkun on 2016/12/29.
 */

public class ActivitySendMix extends K2BaseActivity implements View.OnFocusChangeListener, RadioGroup.OnCheckedChangeListener, View.OnClickListener, NumberPicker.OnValueChangeListener, CompoundButton.OnCheckedChangeListener {
    private CEDevK2Proxy mK2Proxy;
    private NumberPicker mHourPicker, mMinutePicker;
    private int mHour;
    private int mMinute;
    private int week_repeat;
    private int switchState;
    private ArrayList<K2_SendAlarmInfoStruct> mClocks;
    private Handler mK2Handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.arg1 == 0){
                showToast("发送失败，请稍后重试！");
            } else {
                mEtAge.setText("");
                mEtHeight.setText("");
                mEtUserID.setText("");
                showToast("发送成功！");
            }
        }
    };

    private EditText mEtUserID;
    private EditText mEtHeight;
    private EditText mEtAge;
    private Button mSendUserInfo;
    private RadioGroup mRgGender;
    private RadioGroup mRgHandSide;
    private final int MALE = 0;
    private final int FEMALE = 1;
    private final int LEFT_HAND = 0;
    private final int RIGHT_HAND = 1;
    private int mGender = MALE;
    private int mHandSide = RIGHT_HAND;
    private int Height = 0;
    private int Age = 0;
    private int Weight = 0;
    private int mUserId = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_mix_data);
        setTitle("发送混合数据");
        mEtUserID = (EditText) findViewById(R.id.et_user_id);
        mEtHeight = (EditText) findViewById(R.id.et_height);
        mEtAge = (EditText) findViewById(R.id.et_age);
        mRgGender = (RadioGroup) findViewById(R.id.rg_gender);
        mRgHandSide = (RadioGroup) findViewById(R.id.rg_hand_side);
        mSendUserInfo = (Button) findViewById(R.id.btn_send_user_info);
        mEtUserID.setOnFocusChangeListener(this);
        mEtHeight.setOnFocusChangeListener(this);
        mEtAge.setOnFocusChangeListener(this);
        mSendUserInfo.setOnClickListener(this);
        mRgGender.setOnCheckedChangeListener(this);
        mRgHandSide.setOnCheckedChangeListener(this);
        mK2Proxy = BleFactory.getInstance().getK2Proxy();
        mK2Proxy.setHandler(mK2Handler);

        mClocks = new ArrayList<>();
        ((RadioGroup) findViewById(R.id.rg_repeat_day)).setOnCheckedChangeListener(this);
        mHourPicker = ((NumberPicker) findViewById(R.id.np_hour));
        mHourPicker.setOnValueChangedListener(this);
        mHourPicker.setMaxValue(23);
        mHourPicker.setMinValue(0);
        mMinutePicker = ((NumberPicker) findViewById(R.id.np_minute));
        mMinutePicker.setOnValueChangedListener(this);
        mMinutePicker.setMinValue(0);
        mMinutePicker.setMaxValue(59);
        findViewById(R.id.btn_async_alarm).setOnClickListener(this);
        ((Switch) findViewById(R.id.sw_alarm_switch)).setOnCheckedChangeListener(this);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) return;
        switch (v.getId()) {
            case R.id.et_user_id:
                if (!hasFocus) {
                    String input = ((EditText) v).getText().toString();
                    if (isInteger(input)) {
                        mUserId = Integer.parseInt(input);
                    } else {
                        showToast("抱歉，您输入的用户ID不合法");
                    }
                }
                break;


            case R.id.et_age:
                if (!hasFocus) {
                    String input = ((EditText) v).getText().toString();
                    if (checkNum(input, 10, 100)) {
                        Age = Integer.parseInt(input);
                    } else {
                        showToast("抱歉，您输入的年龄不合法");
                    }
                }
                break;

            case R.id.et_height:
                if (!hasFocus) {
                    String input = ((EditText) v).getText().toString();
                    if (checkNum(input, 80, 280)) {
                        Height = Integer.parseInt(input);
                    } else {
                        showToast("抱歉您输入的身高不合法");
                    }
                }
                break;
            case R.id.et_weight:
                if (!hasFocus) {
                    String input = ((EditText) v).getText().toString();
                    if (checkNum(input, 30, 200)) {
                        Weight = Integer.parseInt(input);
                    } else {
                        showToast("抱歉您输入的体重不合法");
                    }
                }
                break;

            default:
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (group.getId()) {
            case R.id.rg_repeat_day:
                switch (checkedId) {
                    case R.id.rb_sunday:
                        week_repeat = 0;
                        break;
                    case R.id.rb_mon:
                        week_repeat = 1;
                        break;
                    case R.id.rb_tuesday:
                        week_repeat = 2;
                        break;
                    case R.id.rb_wednesday:
                        week_repeat = 3;
                        break;
                    case R.id.rb_thursday:
                        week_repeat = 4;
                        break;
                    case R.id.rb_fri:
                        week_repeat = 5;
                        break;
                    case R.id.rb_sat:
                        week_repeat = 6;
                        break;
                    default:
                        break;
                }
                break;
            case R.id.rg_hand_side:
                mHandSide = checkedId == R.id.rb_left_hand ? LEFT_HAND : RIGHT_HAND;
                break;
            case R.id.rg_gender:
                mGender = checkedId == R.id.rb_male ? MALE : FEMALE;
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        if (mK2Proxy.isDisconnect()) {
            showToast("蓝牙已断开，请重新连接");
            return;
        }
        switch (v.getId()) {
            case R.id.btn_send_mix_data:
                if (mUserId != 0 && Age != 0 && Height != 0 && Weight != 0) {
                    K2_SendUserInfo userInfo = new K2_SendUserInfo(mUserId, mGender, Age, Height, Weight, mHandSide);
                    mClocks.clear();
                    K2_SendAlarmInfoStruct alarmInfoStruct = new K2_SendAlarmInfoStruct((byte) week_repeat, (byte) mHour, (byte) mMinute, (byte) switchState);
                    mClocks.add(alarmInfoStruct);

                    ArrayList<K2_MixInfoStruct.Property> properties = new ArrayList<>();
                    byte[] payload = new byte[Send_Alarm_Info_Struct_K3.getItemSize() * mClocks.size() + 1];
                    payload[0] = (byte) mClocks.size();
                    for (int i = 0; i < mClocks.size(); ++i) {
                        K2_SendAlarmInfoStruct this_alrm = mClocks.get(i);
                        byte[] this_alarm_payload = this_alrm.getBytes();
                        System.arraycopy(this_alarm_payload, 0, payload, i * Send_Alarm_Info_Struct_K3.getItemSize() + 1, Send_Alarm_Info_Struct_K3.getItemSize());
                    }
                    K2_MixInfoStruct.Property ar = new K2_MixInfoStruct.Property((byte) CEBC.K2.DATA_TYPE_ALARM, payload);
                    properties.add(ar);
                    properties.add(new K2_MixInfoStruct.Property((byte) CEBC.K2.DATA_TYPE_USERINFO, userInfo.getBytes()));

                    K2_MixInfoStruct mixInfoStruct = new K2_MixInfoStruct(properties);
                    mK2Proxy.getSendHelper().sendMixInfo(mixInfoStruct);

                } else {
                    showToast("您的数据不合法，请重新检查输入");
                    return;
                }



                break;
            case R.id.btn_async_alarm:

                break;

            default:
                break;

        }
    }

    @Override
    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
        switch (picker.getId()) {
            case R.id.np_hour:
                mHour = newVal;
                break;
            case R.id.np_minute:
                mMinute = newVal;
                break;
            default:
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView.getId() == R.id.sw_alarm_switch) {
            switchState = isChecked ? 0 : 1;
        }
    }

    private void showToast(String input) {
        Toast.makeText(this, input, Toast.LENGTH_SHORT).show();
    }

    private boolean checkNum(String input, int min, int max) {
        if (isInteger(input)) {
            int num = Integer.parseInt(input);
            return !(num > max || num < min);
        }
        return false;
    }
}
